Page({
  data: {
    dialogVisible: false,
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '',
    visitDate: '',
    // 指定 `van-datetime-picker` 组件的起始日期
    currentDate: Date.now(),
    maxDate: Date.now() + 3 * 24 * 60 * 60 * 1000,
    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
  },
  onLoad() {
    this.getMyRoomList()
  },
  async getMyRoomList() {
    const { code, data } = await wx.http.get('/room')
    //
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败!')
    const houseList = data.map(({ point, building, room, id }) => {
      return {
        name: `${point} ${building} ${room}室`,
        id,
      }
    })
    this.setData({ houseList })
  },
  // 获取访客来访的时间
  selectDate(ev) {
    this.setData({
      // 隐藏时间弹层
      dateLayerVisible: false,
      visitDate: wx.utils.formatDate(ev.detail),
    })
  },
  selectHouse(ev) {
    // 获取房到的信息数据
    const { id: houseId, name: houseInfo } = ev.detail
    // 页面中渲染
    this.setData({ houseId, houseInfo })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    const { name, houseId, gender, visitDate, mobile } = this.data
    if (!wx.verify.verifyHouse(houseId)) return
    if (!wx.verify.verifyName(name)) return
    if (!wx.verify.verifyMobile(mobile)) return
    if (!wx.verify.verifyDate(visitDate)) return

    // 调用接口
    const { code, data } = await wx.http.post('/visitor', { name, houseId, gender, visitDate, mobile })
    if (code !== 10000) return wx.utils.toast('添加访客信息失败')
    // 去通行证页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  },
})
